<template>
  <div class="article-list" ref="vanList" @scroll="changeScroll">
    <van-pull-refresh v-model="isLoading" @refresh="refresh" v-if="bol">
      <van-list
        v-model="loading"
        @load="getArticles"
        :finished="finished"
        finished-text="没有更多了"
      >
        <article-item :item="i" v-for="i in list" :key="i.art_id" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>
<script>
import { articles } from '@/api/home.js'
import ArticleItem from './article-item.vue'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: ['id'],
  data () {
    return {
      bol: true,
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      timestamp: Date.now(),
      scrollTop: 0
    }
  },
  methods: {
    // 获取文章&&上拉加载
    async getArticles () {
      const res = await articles({
        channel_id: this.id,
        timestamp: this.timestamp
      })
      this.loading = false
      // console.log(res)
      if (res.data.pre_timestamp) {
        this.list.push(...res.data.results)
        this.timestamp = res.data.pre_timestamp
      } else {
        this.finished = true
      }
    },
    // 下拉刷新
    async refresh () {
      this.timestamp = Date.now()
      this.loading = false
      this.finished = false
      this.list = []

      await this.getArticles()
      this.isLoading = false
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    },
    // 列表滚动事件触发保存当前scrollTop值
    changeScroll () {
      // console.log(this.$refs.vanList.scrollTop)
      this.scrollTop = this.$refs.vanList.scrollTop
    }
  },
  async created () {
    // 进到页面调用接口
    // this.getArticles()
  },
  // 显示时
  activated () {
    this.$refs.vanList.scrollTop = this.scrollTop
  }
}
</script>
<style scoped lang="less">
.article-list {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
